home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 8447 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.0 KB

  1. Path: newsfeed.direct.ca!usenet
  2. From: qjackson@direct.ca
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Syntax clarification
  5. Date: Sun, 18 Feb 1996 16:14:58 GMT
  6. Organization: Parsepolis Software
  7. Message-ID: <4g7ja4$spm@aphex.direct.ca>
  8. References: <31236966.1881@sisna.com>
  9. Reply-To: qjackson@direct.ca
  10. NNTP-Posting-Host: 204.174.245.64
  11. X-Newsreader: Forte Free Agent 1.0.82
  12.  
  13. Matt Smolic <msmolic@sisna.com> wrote:
  14.  
  15. >I am just making the switch from C to C++. Something I have come across 
  16. >and cannot find an answer to is the use of the "&" symbol. In C this 
  17. >means the address of, (e.g.) scanf("%d", &Avariable) would return the 
  18. >address of Avariable. In C++ I constantly see syntax such as, in 
  19. >declaring a class, Complex pow(const Complex & c, const Complex & power)
  20. >What does the & symbol do here? 
  21.  
  22. It means that c and power are passed by "reference" -- rather than by
  23. copy.  (That is to say, "c" and "power" are aliases that point to the
  24. actual data, not to a copy of the data.)  There is no need within the
  25. function pow to dereference a pointer, as there is with the *pointer
  26. syntax.
  27.  
  28. Note, however, that the "const" modifier means that, although the
  29. address is passed, the variable may not be modified within the scope
  30. of pow.  This is a method of passing variables quickly, and having the
  31. compiler make certain that the value is not changed  within the
  32. function.  (It prevents a copy being made, which, with large objects,
  33. involves a lot of time and is sometimes semantically deadly.)
  34.  
  35. So:
  36.  
  37. int foo (const int& a, int* b, int c)
  38. {
  39.  
  40.     return a + *b + c;
  41.  
  42. }:
  43.  
  44.  
  45. "Pass a by reference, but don't let anyone change its value within the
  46. function via the alias, pass b as a pointer, requiring explicit
  47. dereferencing within the function to get its value, and pass c as a
  48. copy."
  49.  
  50. Hope this explains things.
  51.  
  52.  
  53. Cheers,
  54.  
  55.  
  56. --                           
  57.                            | 
  58.     Parsepolis Software    |   Quinn Tyler Jackson
  59.         "ParseCity"        |     (aka 'Jamshid')
  60. >--------------------------|   qjackson@direct.ca
  61.                            |---------------------->
  62.  
  63.